package com.atguigu.test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName Demo01
 * @Description 此类描述:死锁案例
 * 死锁描述:吃着碗里的看着锅里的.你等我,我等你
 * @Author dangchen
 * @DateTime 2022-09-16 8:58
 * @Version 1.0
 */
public class Demo01 {
    /*//1.runnable方法
    private static Object objA = new Object();
    private static Object objb = new Object();

    public static void main(String[] args) {
         new Thread(() ->{
             synchronized (objA){
                 System.out.println(Thread.currentThread().getName() + "获得了A锁...");
                 try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}
                 synchronized (objb){
                     System.out.println(Thread.currentThread().getName() + "想获得B锁...");
                 }
             }
         },"A").start();

        new Thread(() ->{
            synchronized (objb){
                System.out.println(Thread.currentThread().getName() + "获得了B锁...");
                try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}
                synchronized (objA){
                    System.out.println(Thread.currentThread().getName() + "想获得A锁...");
                }
            }
        },"B").start();
    }*/

    //2.try-lock
    private static Lock lockA = new ReentrantLock();
    private static Lock lockB = new ReentrantLock();
    public static void main(String[] args) {
        new Thread(() -> {
            lockA.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "获得了A锁...");
                try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}
                lockB.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "想获得B锁...");
                }finally {
                    lockB.unlock();
                }
            }finally {
                lockA.unlock();
            }
        },"A").start();

        new Thread(() -> {
            lockB.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "获得了B锁...");
                try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}
                lockA.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "想获得A锁...");
                }finally {
                    lockA.unlock();
                }
            }finally {
                lockB.unlock();
            }
        },"B").start();
    }
}
